<template>
    <view class="container" style="paddingBottom:1rpx;">
      <u-navbar
			leftIconSize="40rpx"
			leftIconColor="#333333"
			title="账户交易记录"
		>
		</u-navbar>
      <view class="section">
        <view class="section-title">{{ title}}</view>
        <view class="form-view">
          <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="auto"
            :labelStyle="{ color: '#333333', fontSize: '30rpx' }">
            <u-form-item label="记账类型" prop="typeName" required @click="handleAccountType">
              <u--input v-model="form.typeName" disabled disabledColor="#ffffff" placeholder="请选择记账类型"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="记账账户" prop="accountName" required @click="handleAccountName">
              <u--input v-model="form.accountName" disabled disabledColor="#ffffff" placeholder="请选择记账账户"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="交易类型" prop="dealTypeName" required @click="handleDealType">
              <u--input v-model="form.dealTypeName" disabled disabledColor="#ffffff" placeholder="请选择交易类型"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item> 
            <u-form-item label="交易时间" prop="createTime" required @click="selectDate()">
              <u--input v-model="form.createTime" disabled disabledColor="#ffffff" placeholder="请选择交易时间" inputAlign="right" border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>
            <u-form-item label="交易金额" prop="amount" required >
              <u--input v-model="form.amount" type="number" placeholder="请填写交易金额"
                inputAlign="right" border="none"></u--input>
            </u-form-item>
            <u-form-item label="交易类别" prop="dealCategoryName" required @click="handleDealCategory">
              <u--input v-model="form.dealCategoryName" disabled disabledColor="#ffffff" placeholder="请选择交易类别"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="交易子类别" v-show="childCategoryShow" prop="childCategoryName" required @click="handleChildCategory">
              <u--input v-model="form.childCategoryName" disabled disabledColor="#ffffff" placeholder="请选择交易子类别"
                inputAlign="right" border="none"></u--input>
              <u-icon slot="right" name="arrow-down"></u-icon>
            </u-form-item>
            <u-form-item label="备注" prop="remark"  labelPosition="top">
              <u--textarea v-model="form.remark" placeholder="请填写备注" border="none" autoHeight inputAlign="right" count
                maxlength="20000" style="padding:18rpx 0;"></u--textarea>
            </u-form-item>
          </u--form>
          <view class="form-btn">
            <u-button type="primary" text="提交" @click="submit"></u-button>
          </view>
        </view>
      </view>
      <u-toast ref="uToast"></u-toast>
      <u-picker itemHeight="88" :show="showAccountType" :columns="accountTypeList" keyName="dictLabel" @cancel="handleAccountTypeCancel"
        @confirm="handleAccountTypeConfirm"></u-picker>
        <u-picker itemHeight="88" :show="showAccountName" :columns="accountNameList" keyName="nameCodeAvailableLimit" @cancel="handleAccountNameCancel"
        @confirm="handleAccountNameConfirm"></u-picker>
        <u-picker itemHeight="88" :show="showDealCategory" :columns="dealCategoryList" keyName="dictLabel" @cancel="handleDealCategoryCancel"
        @confirm="handleDealCategoryConfirm"></u-picker>

        <u-picker itemHeight="88" :show="showChildCategory" :columns="childCategoryList" keyName="dictLabel" @cancel="handleChildCategoryCancel"
        @confirm="handleChildCategoryConfirm"></u-picker>

        <u-picker itemHeight="88" :show="showDealType" :columns="dealTypeList" keyName="dictLabel" @cancel="handleDealTypeCancel"
        @confirm="handleDealTypeConfirm"></u-picker>
        <u-datetime-picker
			:show="datePickShow"
			mode="datetime"
      ref="createTimeRef" 
			@cancel="datePickShow=false"
			@confirm="datePickConfirm"
			itemHeight="88"
		></u-datetime-picker>
    </view>
  </template>
  
  <script setup>
  import {getAccountDealRecord, addAccountDealRecord, updateAccountDealRecord } from '@/api/invest/accountDealRecord'
  import { getDicts } from '@/api/system/dict/data.js'
  import { listAccounts } from '@/api/invest/accounts'
  const { proxy } = getCurrentInstance()
  import dayjs from 'dayjs'
  import {onLoad,onReady} from "@dcloudio/uni-app";
    // 计算属性与监听属性是在vue中而非uniap中 需要注意！！！
import {reactive ,toRefs,ref,computed ,getCurrentInstance }from "vue";
const datePickShow = ref(false)
const showAccountType = ref(false)
const showAccountName = ref(false)
const showDealCategory = ref(false)
const showChildCategory = ref(false)
const showDealType = ref(false)
const title = ref("账户交易记录")
const accountTypeList = ref([])
const accountNameList = ref([])
const dealCategoryList = ref([])
const childCategoryList = ref([])
const childCategoryShow = ref(true)
const flag = ref('add')
const dealTypeList = ref([])
const data = reactive({
  form: {
    id: null,
    name: null,
    type: '1',
    accountId: null,
    amount: 0,
    dealType: '2',
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    remark: null,
    currentBalance: null,
    dealCategory: '1',
    childCategory: null
  },
  queryAccountParams: {
    pageNum: 1,
   status: '1', 
    type: '1',
    pageSize: 1000
  },
  rules: {
    typeName: [{ required: true, message: '记账类型不能为空', trigger:['change', 'blur'] }],
    accountName: [{ required: true, message: '记账账户不能为空', trigger: ['change', 'blur'] }],
    amount: [{type: 'number', required: true, message: '交易金额不能为空', trigger: ['change', 'blur'] }],
    dealTypeName: [{ required: true, message: '交易类型不能为空', trigger:['change', 'blur'] }],
    dealCategoryName: [{ required: true, message: '交易类别不能为空', trigger: ['change', 'blur'] }],
    childCategoryName: [{ required: true, message: '交易子类别不能为空', trigger: ['change', 'blur'] }],
    createTime: [{ required: true, message: '交易时间不能为空', trigger: ['change', 'blur'] }]
  }
})
const { form, queryAccountParams, rules} = toRefs(data)


onLoad((option) => {
       form.value.id = option.id
       flag.value = option.flag
     if(flag.value==null){
      if(form.value.id!=null){
      title.value="账户交易记录-修改"
     }else{
      title.value="账户交易记录-新增"
     }
     }else{
      title.value="账户交易记录-复制"
     }
     
  })
  onReady(() => {
    form.value.createTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
    getData()
  })
  function  getData() {
   
        // 类型
        getDicts('account_type').then(res => {
        accountTypeList.value =[res.data] 
      })
       // 类型
       getDicts('deal_type').then(res => {
        dealTypeList.value =[res.data] 
      })
       // 类型
       getDicts('deal_category').then(res => {
        dealCategoryList.value =[res.data] 
      })
       // 子类型
       getDicts('daily_expenses').then(res => {
        childCategoryList.value =[res.data] 
      })

      listAccounts(queryAccountParams.value).then((response) => {
    accountNameList.value = [response.rows] 
  })
        // 交易类别
        getDicts('daily_expenses').then(result => {
          form.value.childCategoryName=dictStr(form.value.childCategory, result.data)
         })
          // 交易类别
        getDicts('deal_category').then(result => {
          form.value.dealCategoryName=dictStr(form.value.dealCategory, result.data)
         })
          // 记账类型
           getDicts('account_type').then(result => {
          form.value.typeName=dictStr(form.value.type, result.data)
         })
                // 交易类型
                getDicts('deal_type').then(result => {
          form.value.dealTypeName=dictStr(form.value.dealType, result.data)
         })
    
      if(form.value.id!=null){
        getAccountDealRecord(form.value.id).then(res => {
          form.value = res.data
          if (form.value.dealCategory === '1') {
    childCategoryShow.value = true
             // 交易类别
getDicts('daily_expenses').then(result => {
          form.value.childCategoryName=dictStr(form.value.childCategory, result.data)
         })
  } else {
    form.value.childCategoryName = form.value.childCategory
    childCategoryShow.value = false
  }
// 交易类别
getDicts('deal_category').then(result => {
          form.value.dealCategoryName=dictStr(form.value.dealCategory, result.data)
         })

          // 记账类型
           getDicts('account_type').then(result => {
          form.value.typeName=dictStr(form.value.type, result.data)
         })
          // 交易类型
          getDicts('deal_type').then(result => {
          form.value.dealTypeName=dictStr(form.value.dealType, result.data)
         })
         if(form.value.type=='1'||form.value.type=='2'){
          queryAccountParams.value.type = form.value.type
         }
         else {
          queryAccountParams.value.type = null
         }
         
         if(flag.value!=null){
        form.value.createTime = dayjs(new Date().getTime()).format("YYYY-MM-DD HH:mm:ss")
       }
        listAccounts(queryAccountParams.value).then((response) => {
          accountNameList.value = [response.rows] 
         })    
        })
      }
  }
  function dictStr(val, arr) {
      let str = ''
      arr.map(item => {
        if (item.dictValue === val) {
          str = item.dictLabel
        }
      })
      return str
    }

  function handleAccountType() {
        if (accountTypeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '记账类型为空  ', type: 'warning'
          })
        } else {
          showAccountType.value = true
        }
     }
  function   handleAccountTypeConfirm(e) {
        form.value.typeName = e.value[0].dictLabel
        form.value.type = e.value[0].dictValue
        queryAccountParams.value.type = form.value.type
        form.value.accountId = null
        form.value.accountName = null
        listAccounts(queryAccountParams.value).then((response) => {
          accountNameList.value = [response.rows] 
         })
        showAccountType.value = false
        
  }
 function handleAccountTypeCancel() {
       showAccountType.value = false
      }
      function handleAccountName() {
        if (accountNameList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '记账账户为空  ', type: 'warning'
          })
        } else {
          showAccountName.value = true
        }
     }
  function   handleAccountNameConfirm(e) {
        form.value.accountName = e.value[0].nameCodeAvailableLimit
        form.value.accountId = e.value[0].id
        showAccountName.value = false
  }
 function handleAccountNameCancel() {
       showAccountName.value = false
  }
  function handleDealCategory() {
        if (dealCategoryList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '交易类别为空  ', type: 'warning'
          })
        } else {
          showDealCategory.value = true
        }
     }
  function   handleDealCategoryConfirm(e) {
        form.value.dealCategoryName = e.value[0].dictLabel
        form.value.dealCategory = e.value[0].dictValue
         //1表示日常支出，如果是日常支出，选择子类别，否则不显示子类别，且子类别与类别相同
  if (form.value.dealCategory === '1') {
    form.value.childCategory = null
    childCategoryShow.value = true
  } else {
    childCategoryShow.value = false
    form.value.childCategory = form.value.dealCategory
    form.value.childCategoryName = form.value.dealCategory
  }
        showDealCategory.value = false
  }
 function handleDealCategoryCancel() {
      showDealCategory.value = false
      }

      function handleChildCategory() {
        if (childCategoryList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '交易子类别为空  ', type: 'warning'
          })
        } else {
          showChildCategory.value = true
        }
     }
  function   handleChildCategoryConfirm(e) {
        form.value.childCategoryName = e.value[0].dictLabel
        form.value.childCategory = e.value[0].dictValue
        showChildCategory.value = false
  }
 function handleChildCategoryCancel() {
  showChildCategory.value = false
      }

  function handleDealType() {
        if (dealTypeList.value[0].length === 0) {
          proxy.$refs['uToast'].show({
            message: '交易类型为空  ', type: 'warning'
          })
        } else {
          showDealType.value = true
        }
     }
  function   handleDealTypeConfirm(e) {
        form.value.dealTypeName = e.value[0].dictLabel
        form.value.dealType = e.value[0].dictValue
        showDealType.value = false
  }
 function handleDealTypeCancel() {
       showDealType.value = false
      }
  function  selectDate() {
				datePickShow.value = true
        proxy.$refs['createTimeRef'].innerValue = new Date().getTime()
		}
	function datePickConfirm(e) {
				form.value.createTime = dayjs(e.value).format("YYYY-MM-DD HH:mm:ss")
				datePickShow.value = false
		}
  function submit() {
        proxy.$refs['uForm'].validate().then(() => {
          if (form.value.id != null) {
            if(flag.value==null){
            updateAccountDealRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '修改成功', complete() {
              uni.navigateTo({ url: `/pages/work/accounts/accountDealRecord/list` })
            }
          })
        })
          }else {
            form.value.id == null
            addAccountDealRecord(form.value).then(res => {
            proxy.$refs['uToast'].show({
            message: '新增成功', complete() {
              uni.navigateTo({ url: `/pages/work/accounts/accountDealRecord/list` })
            }
          })
        })
          }
          }else {
            addAccountDealRecord(form.value).then(res => {
              proxy.$refs['uToast'].show({
              message: '新增成功', complete() {
                uni.navigateTo({ url: `/pages/work/accounts/accountDealRecord/list` })
              }
            })
          })
          }
        })
      }
  </script>
  
  <style lang="scss" scoped>
  .section {
    margin: 24rpx;
    padding: 16rpx 24rpx;
    background-color: #fff;
    border-radius: 8rpx;
  
    .section-title {
      width: 360rpx;
      color: #333333;
      line-height: 44rpx;
      font-size: 30rpx;
      border-left: 6rpx solid #2681FF;
      padding-left: 26rpx;
    }
  
    .form-view {
      padding: 20rpx 0rpx 0 10rpx;
  
      .form-btn {
        padding-top: 20rpx;
      }
    }
  }
  </style>